// subpacks/pages_first/faceSignIn/faceDetect/faceDetect.js
let appg = getApp().globalData
import Dialog from '@vant/weapp/dialog/dialog';
import {
  splitBase64IntoChunks
} from '../../../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StartEntry: true,
    src: null,
    imgType: null,
    uid:null,
    sid:null,
    className:null,
    username:null
  },
  // 开始拍照
  takePhoto() {
    this.AudioContext.stop() // 停止
    let _this = this
    this.ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          src: res.tempImagePath,
          StartEntry: false
        })
        console.log(res.tempImagePath);
        // 如果需要获取图片类型的话
        wx.getImageInfo({
          src: res.tempImagePath,
          async success(json) {
            console.log(json);
            _this.setData({
              imgType: json.type
            })
          }
        });
      }
    })
  },
  error(e) {
    console.log(e.detail)
  },
  // 上传图片
  async Upload() {
    let imgBase64 = null;
    // 转base64
    const fs = wx.getFileSystemManager()
    // 同步接口
    try {
      const res_base64 = fs.readFileSync(this.data.src, 'base64', 0)
      console.log("人脸的base64：", res_base64)
      imgBase64 = res_base64
    } catch (e) {
      wx.showToast({
        title: e,
      })
    };
    wx.showLoading({
      title: '人脸图片检验中~',
      mask: true
    });
    let chunks = splitBase64IntoChunks(imgBase64, 1024 * 64)
    console.log(chunks);
    // return
    const socket = wx.connectSocket({
      url: appg.ws,
      success() {
        console.log("socket 服务器连接成功");
      },
      fail() {
        console.log("socket 服务器连接失败");
      }
    });
    socket.onOpen((res) => {
      socket.send({
        data: JSON.stringify({
          event: 'imgName',
          data: appg.userInfo.username+"sign"+ '.' + this.data.imgType
        })
      });
      socket.onMessage(async (data) => {
        const json = JSON.parse(data.data)
        console.log("服务器返回来的数据:", json);
        if (json.event == "sentImgUrl") {
          // 进行人脸检测
          let result = await getApp().$axios("/faceDetect", "POST", {
            Url: 'https://' + json.data.imgUrl
          });
          console.log("人脸检测的结果", result);
          if (result.status == 400 && result.data.code == "InvalidParameterValue.NoFaceInPhoto") {
            wx.showModal({
              title: "检测结果",
              content: '图片中没有检测到人脸请重新拍照！',
              showCancel: false,
              complete: (res) => {
                this.beginEntry()
              }
            })
          } else {
            if (result.data.FaceInfos[0].FaceAttributesInfo.Mask) {
              wx.showModal({
                title: '结果',
                content: '请摘下口罩重新拍！',
                showCancel: false,
                complete: (res) => {
                  this.beginEntry()
                }
              })
              return;
            }
            try {
              // 开始比对人脸
              const result = await getApp().$axios("/faceCompare", "POST", {
                id: appg.userInfo.id,
                url: 'https://' + json.data.imgUrl
              })
              if (result.status !== 200) {
                Dialog.alert({
                  title: '标题',
                  message: result.data,
                }).then(() => {
                  // on close
                  this.beginEntry()
                });
                return
              }
              console.log(result);
              const Score = result.data.data.Score;
              console.log(Score);
              if (Score<50) {
                // 不是同一个人
                Dialog.alert({
                  title: '提示',
                  message:"人脸识别到不是同一个人，请重试",
                }).then(() => {
                  // on close
                  this.beginEntry()
                });
              }else if (50 <= Score && Score <= 70) {
                Dialog.alert({
                  title: '提示',
                  message:"识别度很高但是还差点意思，请重试",
                }).then(() => {
                  // on close
                  this.beginEntry()
                });
              }else{
                // 识别成功 更改签到表的签到状态 返回上一层
                const params = {
                  status:1,
                  uid:this.data.uid,
                  sid:this.data.sid,
                  username:this.data.username,
                  className:this.data.className,
                  faceUrl:'https://' + json.data.imgUrl
                }
                const res = await getApp().$axios("/changeSignInfo","POST",params)
                 if (res.status!==200) {
                   wx.showToast({
                     title: res.data,
                     icon:'none'
                   })
                   return
                 }
                 console.log(res,"签到状态");
                 if (res.data[0]==1) {
                  Dialog.alert({
                    title: '提示',
                    message:"签到成功",
                  }).then(() => {
                    // on close
                    // wx.redirectTo({
                    //   url: '../faceSignIn?sid='+this.data.sid,
                    // })
                    wx.navigateBack({
                      delta:1
                    })
                  });
                 }
              }
            } catch (error) {
              wx.showToast({
                title: error.msg,
                icon: 'error'
              })
            }

            // 关闭连接
            socket.close({
              code: 1000
            })
          }
        }
      });
      // 逐个发送块数据
      chunks.forEach((chunk, index) => {
        let eventData = {
          event: 'base64Data', // 事件标识字段
          data: chunk
        };
        setTimeout(() => {
          socket.send({
            data: JSON.stringify(eventData),
            success: () => {
              console.log(`块 ${index + 1}/${chunks.length} 已发送`);
              if (index === chunks.length - 1) {
                // 所有块数据已发送，发送结束消息
                socket.send({
                  data: JSON.stringify({
                    data: {},
                    event: 'upload_complete'
                  }),
                  success: () => {
                    console.log('上传完成');
                    // 关闭定时器或执行其他操作
                    wx.hideLoading()
                  },
                });
              };
            },
          });
        }, index * 200); // 延迟发送以避免过快发送
      });

      socket.onError((error) => {
        console.log("错误信息：", error);
      });
      socket.onClose((code, reason) => {
        console.log("一个数字值表示关闭连接的状态号，表示连接被关闭的原因。:", code, "表示连接被关闭的原因。", reason);
      })
    })
  },
  // 重新录入
  beginEntry() {
    this.setData({
      StartEntry: true
    });
    this.AudioContext.play()
    this.AudioContext.onPlay(() => {
      console.log('开始播放')
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 加载相机
    this.ctx = wx.createCameraContext()
    // 创建音频播放
    this.AudioContext = wx.createInnerAudioContext()
    this.AudioContext.src = 'images/mp3/1695452017118.mp3'
    this.AudioContext.play()
    this.AudioContext.onPlay(() => {
      console.log('开始播放')
    })
    const sid = options.sid
    console.log(appg.userInfo);
    this.setData({
      sid,
      uid:appg.userInfo.id,
      className:appg.userInfo.class_name,
      username:appg.userInfo.username,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})